package strategies

import (
	"fmt"
	"time"

	"monitor.ilin.cc/internal/pkg/indicators"
	"monitor.ilin.cc/internal/pkg/strategy"
)

// MA交叉策略配置
type MACrossConfig struct {
	FastPeriod  int           // 快线周期
	SlowPeriod  int           // 慢线周期
	MinInterval time.Duration // 最小交易间隔
}

// 默认配置
var DefaultMACrossConfig = MACrossConfig{
	FastPeriod:  5,
	SlowPeriod:  20,
	MinInterval: 1 * time.Hour,
}

// 均线交叉策略
type MACrossStrategy struct {
	symbol    string
	config    MACrossConfig
	fastMA    *indicators.MA
	slowMA    *indicators.MA
	lastTrade time.Time // 上次交易时间
	position  bool      // true表示持有
}

func NewMACrossStrategy(symbol string, config *MACrossConfig) *MACrossStrategy {
	cfg := DefaultMACrossConfig
	if config != nil {
		cfg = *config
	}

	return &MACrossStrategy{
		symbol: symbol,
		config: cfg,
		fastMA: indicators.NewMA(cfg.FastPeriod),
		slowMA: indicators.NewMA(cfg.SlowPeriod),
	}
}

func (s *MACrossStrategy) GetSymbol() string {
	return s.symbol
}

func (s *MACrossStrategy) Update(price float64, timestamp time.Time) (*strategy.Signal, error) {
	// 更新指标
	if err := s.fastMA.Update(price); err != nil {
		return nil, fmt.Errorf("更新快速MA失败: %v", err)
	}
	if err := s.slowMA.Update(price); err != nil {
		return nil, fmt.Errorf("更新慢速MA失败: %v", err)
	}

	// 获取指标值
	fastValue := s.fastMA.GetValue()
	slowValue := s.slowMA.GetValue()

	// 检查交易间隔
	if time.Since(s.lastTrade) < s.config.MinInterval {
		return nil, nil
	}

	// 生成信号
	if fastValue > slowValue && !s.position {
		// 金叉买入信号
		s.position = true
		s.lastTrade = timestamp
		return &strategy.Signal{
			Type:      strategy.BuySignal,
			Price:     price,
			Timestamp: timestamp,
			Reason:    fmt.Sprintf("MA金叉：快线(%.2f) 上穿 慢线(%.2f)", fastValue, slowValue),
		}, nil
	} else if fastValue < slowValue && s.position {
		// 死叉卖出信号
		s.position = false
		s.lastTrade = timestamp
		return &strategy.Signal{
			Type:      strategy.SellSignal,
			Price:     price,
			Timestamp: timestamp,
			Reason:    fmt.Sprintf("MA死叉：快线(%.2f) 下穿 慢线(%.2f)", fastValue, slowValue),
		}, nil
	}

	return nil, nil
}

func (s *MACrossStrategy) Reset() {
	s.fastMA.Reset()
	s.slowMA.Reset()
	s.position = false
}
